import React, { useState, useRef, useEffect } from 'react';
import { Input, Button, message } from 'antd';
import { MinusCircleOutlined } from '@ant-design/icons';

export default function text() {
  // 3、js随机
  // 用 js 实现随机选取 10-100 之间的 10 个数字，存入一个数组，去重后求和（保证这 10 个数字不能出现重复）
  function randomCount() {
    let count = 0;
    const arr = Array(10)
      .fill('1')
      .map(() => 10 + Math.floor(Math.random() * 90)); //随机数  包含10  不包含100

    [...new Set(arr)].forEach((item) => (count += item));

    console.log(arr, count);
  }

  const [list, setList] = useState(1);

  function logList() {
    const inputs = document.querySelectorAll(
      '.inputs',
    ) as unknown as HTMLInputElement[];
    const arr: string[] = [];
    inputs.forEach((e: HTMLInputElement) => {
      arr.push(e.value);
    });
    console.log('值列表 : ', arr);
  }
  const [countDown, setCountDown] = useState(10);
  const [cardDataList, setCardDataList] = useState(initCardDataList);
  useEffect(() => {
    const Timer = setInterval(() => {
      setCountDown(countDown - 1);
    }, 10);
    return () => {
      clearInterval(Timer);
    };
  });
  function buyingSpree(index: number) {
    const newData = JSON.parse(JSON.stringify(cardDataList));
    newData[index].loading = true;
    setCardDataList(newData);
    console.log(newData[index], cardDataList);

    setTimeout(() => {
      message.success('抢购成功');
      const newData = JSON.parse(JSON.stringify(cardDataList));
      newData[index].loading = false;
      setCardDataList(newData);
    }, 1000);
  }

  function compart(v1: string, v2: string) {
    const v1Arr = handleArr(v1.split('.'));
    const v2Arr = handleArr(v2.split('.'));
    for (let i = 0; i < 4; i++) {
      if (v1Arr[i] > v2Arr[i]) return 1;
      if (v1Arr[i] < v2Arr[i]) return -1;
    }
    return 0;
  }
  function handleArr(arr: String[], lenNum = 4) {
    if (!Array.isArray(arr)) return [];
    const newArr = arr.map((i) => Number(i));
    newArr.forEach((i) => {
      if (isNaN(i)) return '有非数字';
    });
    const len = newArr.length;
    if (len < lenNum) {
      for (let i = 0; i < lenNum - len; i++) {
        newArr.push(0);
      }
    }
    if (len > lenNum) {
      newArr.splice(4);
    }

    return newArr;
  }
  function urlSplit(url: string) {
    //decodeURIComponent(key)
    //const url = '?name=feizhu&from=alibaba&job=frontend&extraInfo=%7B%22a%22%3A%22b%22%2C%22c%22%3A%22d%22%7D&china=%E4%B8%AD%E5%9B%BD#id';
    let result = '';
    const resultObj: any = {};
    if (url.indexOf('?') > -1) {
      result = url.split('?')[1];
    } else {
      result = url;
    }
    result.indexOf('#') > -1 && (result = result.split('#')[0]);

    result.split('&').forEach((item) => {
      const arr = item.split('=');
      resultObj[arr[0]] = decodeURIComponent(arr[1]);
    });
    console.log(resultObj);
  }
  return (
    <div className="white-list-text">
      <button onClick={randomCount}>10-100的随机数</button>
      <div className="white-list-text-list">
        <div>
          Passengers:
          {list && (
            <ul>
              {Array(list)
                .fill('1')
                .map((item, index) => {
                  return (
                    <li key={index}>
                      <Input placeholder="passenger name" className="inputs" />
                      <MinusCircleOutlined
                        className="white-list-text-list-iconJ"
                        onClick={() => {
                          list && setList((pre) => pre - 1);
                        }}
                      />
                    </li>
                  );
                })}
            </ul>
          )}
        </div>
        <p
          className="white-list-text-list-p"
          onClick={() => {
            setList((pre) => pre + 1);
          }}
        >
          + Add field
        </p>
        <button onClick={logList}>点击打印值列表</button>
      </div>
      <div className="white-list-text-shopping">
        {cardDataList.length &&
          cardDataList.map((item, index) => (
            <div className="white-list-text-shopping-block">
              <p>
                <img src={item.brandLogo} alt="" /> {item.brandName}
              </p>
              <div className="white-list-text-shopping-block-content">
                <img src={item.campImage} alt="" />
                <div className="white-list-text-shopping-block-content-center">
                  {item.promoLogo.map((ii) => (
                    <img src={ii} alt="" />
                  ))}
                  <p>{item.voucherDesc}</p>
                  <p>{item.benefitAmount}</p>
                </div>
                <div className="white-list-text-shopping-block-content-right">
                  {countDown >= 0 ? (
                    <div className="count-down">
                      <p>倒计时</p>
                      <span>{countDown}</span>
                    </div>
                  ) : (
                    <Button
                      onClick={() => {
                        buyingSpree(index);
                      }}
                      loading={item.loading}
                    >
                      抢购
                    </Button>
                  )}
                </div>
              </div>
            </div>
          ))}
      </div>
      <div>
        <button
          onClick={() => {
            console.log(compart('10.2.1.1.1.4', '10.2.1.4'));
          }}
        >
          版本号
        </button>
        <button
          onClick={() => {
            urlSplit(
              '?name=feizhu&from=alibaba&job=frontend&extraInfo=%7B%22a%22%3A%22b%22%2C%22c%22%3A%22d%22%7D&china=%E4%B8%AD%E5%9B%BD#id',
            );
          }}
        >
          url转换
        </button>
      </div>
    </div>
  );
}
const initCardDataList = [
  {
    brandName: '弄堂里',
    brandLogo:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*anNdQqA_I_AAAAAAAAAAAAAAARQnAQ',
    distanceDesc: '500m',
    campImage:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*U29sSqgeU-4AAAAAAAAAAAAAARQnAQ',
    promoLogo: [
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*y6CTRo9L2oEAAAAAAAAAAAAAARQnAQ',
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*Q1d4SIoeKRkAAAAAAAAAAAAAARQnAQ',
    ],
    voucherDesc: '弄堂里14元超值优惠券包x2',
    benefitAmount: '1',
    oriPriceAmount: '28',
    discountDesc: '0.6折',
    voucherStockNum: '库存888份',
    loading: false,
  },
  {
    brandName: '弄堂里',
    brandLogo:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*anNdQqA_I_AAAAAAAAAAAAAAARQnAQ',
    distanceDesc: '500m',
    campImage:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*U29sSqgeU-4AAAAAAAAAAAAAARQnAQ',
    promoLogo: [
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*Q1d4SIoeKRkAAAAAAAAAAAAAARQnAQ',
    ],
    voucherDesc: '弄堂里14元超值优惠券包x2',
    benefitAmount: '1',
    discountDesc: '0.6折',
    loading: false,
  },
  {
    brandName: '飞猪',
    brandLogo:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*dCL5Q4oBaQsAAAAAAAAAAAAAARQnAQ',
    campImage:
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*MZ7VSaNZXRYAAAAAAAAAAAAAARQnAQ',
    promoLogo: [
      'https://gw.alipayobjects.com/mdn/rms_7527d7/afts/img/A*90WEQLmnKdkAAAAAAAAAAAAAARQnAQ',
    ],
    voucherDesc: '南方航空20元优惠券',
    benefitAmount: '20',
    loading: false,
  },
];
